<?php
require("dbFunctions.php");	//Needed to create a new QR Code. Requiring this requires connectDB

/**
 * Adds a new piece of equipment to the database.
 * This file should be hidden from users using the web interface and is used to populate the database
 * from the mobile device specifically.
 *
 * Author: Armand Pallino
 * Date: 10/27/2012
 */

//Get the parameters
$equipment_name = $_REQUEST['equip_name'];
$serial_number = $_REQUEST['serial_num'];
$current_condition = $_REQUEST['condition'];

//Verify that equipment name, serial number, and 
//current condition are non-null.
if( is_null($equipment_name) )
	die("No equipment name provided.");
if( is_null($serial_number) )
	die("No serial number provided.");
if( is_null($current_condition) )
	die("No condition provided.");

//Get a PDO Database connection
$dbh = connectDB();

//Look for this item in the table already and get it's QR_Code.
$qr_code =  equipmentIDByTypeAndSN($equipment_name, $serial_number);
//If it doesn't exist, create a new QR_Code for this piece of Equipment.
// and add it to the table
if( $qr_code == -1 )
{
	$qr_code = createNewQREntry("Equipment");

	//Construct the query to add a new piece of Equipment
	$query =  "INSERT INTO Equipment (qr_code, equipment_name, serial_number, current_condition) VALUES (:qr_code, :equip_name, :serial_num, :condition)";

	//Create a PDO Statement by preparing the query
	$stmt = $dbh->prepare( $query );
	//Bind parameters to avoid SQL injection
	$stmt->bindParam(':qr_code', $qr_code);
	$stmt->bindParam(':equip_name', $equipment_name);
	$stmt->bindParam(':serial_num', $serial_number);
	$stmt->bindParam(':condition', $current_condition);

	//Execute the PDO Statement
	$stmt->execute();
}
//Otherwise it already existed, so make sure that code is considered active
else
{	
	$query = "UPDATE QR_Code SET is_active=1 WHERE qr_code=:qr_code";
	$stmt = $dbh->prepare($query);
	$stmt->bindParam(':qr_code',$qr_code);
	$stmt->execute();
}

//Release the PDO Statement and PDO database connection
$stmt = null;
$dbh = null;

print($qr_code);
?>
